const util = require('../../utils/util.js')
const config = require('../../config.js')
//index.js
//获取应用实例
const app = getApp()

Page({
  data: {
    shake:'',
    focus:'focus',
    address:'',
    latitude:0,
    longitude:0,
    addr_name:'',
    showAddress:false,
    text:'',
    images: [],
    temImages: [],
    imagesCount:0,
    voiceRecord:false,
    personalIndex:0,
    personalOptions:['不公开','公开']

  },
  chooseImage: function (e) {
    var that = this;
    wx.chooseImage({
      sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图，默认二者都有
      sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机，默认二者都有
      success: function (res) {
        // that.setData({ 'images': [] });
        // that.setData({ 'temImages': [] });
        // 返回选定照片的本地文件路径列表，tempFilePath可以作为img标签的src属性显示图片
        that.setData({
          temImages: that.data.temImages.concat(res.tempFilePaths),
          imagesCount: ++that.data.imagesCount
        });
         //上传图片
        that.data.temImages.forEach(function (path) {
          console.log(path);
          wx.uploadFile({
            url: config.updateImageUrl, //接口地址
            header: { 'content-type': 'multipart/form-data' },
            filePath: path,
            name: 'file',
            success: function (res) {
              var currentImages = that.data.images;
              if(res.statusCode==200){
                var rs = JSON.parse(res.data);
                if (rs.state) {
                  currentImages.push({ path: rs.data })
                } else {
                  that.uploadImageFaild(path);
                }
                that.setData({ 'images': currentImages })
              }else{
                that.uploadImageFaild(path);
              }
            },
            fail: function (res) {
            }
          })
        });
      }
    })
  },
  uploadImageFaild: function(path){
    console.log('file is too large. '+path);
    var temImages = this.data.temImages;
    temImages.pop();
    this.setData({ 'temImages': temImages });
  },
  previewImage: function (e) {
    wx.previewImage({
      current: e.currentTarget.id, // 当前显示图片的http链接
      urls: this.data.images // 需要预览的图片http链接列表
    })
  },
  textinput:function(e){
    this.setData({ text: e.detail.value})
  },
  saveBtnTap: function(){
    var _this = this;
    if (_this.data.address || _this.data.showAddress || _this.data.text){
      
      wx.showLoading({
        success: function(){
          //保存到服务器
          var date = new Date();
          var datetime = util.formatTime(date);
          var notes = wx.getStorageSync('notes') || [];
          var note = {
            'content': _this.data.text,
            'address': _this.data.addr_name,
            'addr_name': _this.data.addr_name,
            'longitude': _this.data.longitude,
            'latitude': _this.data.latitude,
            'images': _this.data.images,
            'personal': _this.data.personalOptions[_this.data.personalIndex],
            'datetime': datetime,
            'timestamp': date.getTime(),
            'userId': 1
          };
          notes.push(note);
          wx.setStorageSync('notes', notes);
          _this.submitNote();
          wx.hideLoading();
          wx.navigateBack({
            delta: 1
          })
        }
      })
      
    }else{
      var _this = this;
      this.setData({ shake: 'shake', focus:'focus'});
      setTimeout(function () { _this.setData({ shake: '' });},1000);
    }
  },
  submitNote: function(){
    var _this = this;
    var notes = wx.getStorageSync('notes') || [];
    if(notes.length>0){
      notes.forEach(function(note){
        util.uploadNote(note, _this.uploadCB);
      })
    }
  },
  uploadCB: function(note,isUploaded){
    if (!isUploaded){
      return;
    }
    var notes = wx.getStorageSync('notes') || [];
    if(notes.length > 0) {
      var rm_index = null;
      notes.forEach(function(val,index){
        if (val.timestamp == note.timestamp){
          rm_index = index;
        }
      })
      if (null != rm_index){
        //在缓存的数据中清除已经处理成功的
        console.log(note)
        console.log('isUploaded:' + isUploaded)
        notes.splice(rm_index,1)
        wx.setStorageSync('notes', notes)
      }
    }
   
    // TODO 从Storage中移除已经上传的数据
    // TODO 如果Storage中存在未上传的数据，那么上传它
  
  },
  disableLocation: function(e){
    console.log('disable');
      this.setData({
        showAddress: !this.data.showAddress
      })
  },
  selectLocation:function(e){
    var targetid = e.target.id;
    console.log(targetid)
    if ((targetid === 'disableLocation')){
      if (this.data.addr_name){ 
        this.setData({
          showAddress: !this.data.showAddress
        })
        return;
      }
    }
    var _this=this;
    wx.chooseLocation({
      success :function(res){
        _this.setData({
          'address' : res.address,
          'latitude' : res.latitude,
          'longitude' : res.longitude,
          'addr_name' : res.name,
          'showAddress': true
        })
        console.log(res.name);
      },
      fail : function(e){
        _this.setData({
          showAddress:false
        })
        console.log('faild');
        console.log(e);
      },
      complete : function(){
        console.log('complete...');
      }
    })
  },
  bindPersonalChange :function(e){
    this.setData({ personalIndex: e.detail.value});
  },
  onLoad: function () {
    wx.setTopBarText({text:'my note.'});
    wx.setNavigationBarTitle({ title: 'my note.' });
    this.submitNote();
  }
})
